//
//  ColorEngine.m
//  ChinaBookingPhone
//
//  Created by 杨 锐 on 14-5-21.
//  Copyright (c) 2014年 xingheng. All rights reserved.
//

#import "UIColor+Extensions.h"

@implementation UIColor (Extensions)

/**
 *  16进制颜色值转RGB
 *
 *  @param aHexStr 色值
 *
 *  @return 返回UIColor
 */
+ (UIColor*)HexStrWithColor:(NSString *)aHexStr
{
    unsigned int r, g, b,a=1.0f;
    
    /* 过滤 */
    if ([aHexStr hasPrefix:@"0X"])
        aHexStr = [aHexStr substringFromIndex:2];
    if ([aHexStr hasPrefix:@"#"])
        aHexStr = [aHexStr substringFromIndex:1];
    
    /* 取子串 */
    NSRange range;
    range.length = 2;
    
    //r
    range.location = 0;
    NSString *rString = [aHexStr substringWithRange:range];
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    
    //g
    range.location = 2;
    NSString *gString = [aHexStr substringWithRange:range];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    
    //b
    range.location = 4;
    NSString *bString = [aHexStr substringWithRange:range];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    //Alpha
    if ([aHexStr length] ==8)
    {
        range.location = 6;
        NSString *aString = [aHexStr substringWithRange:range];
        [[NSScanner scannerWithString:aString] scanHexInt:&a];
    }
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:a];
}

/**
 *  RBG转16进制色值
 *
 *  @param color UIColor颜色
 *
 *  @return 返回16进制色值
 */
+ (NSString*)colorWithHexStr:(UIColor*)color{
    
    CGFloat r, g, b, a;
    [color getRed:&r green:&g blue:&b alpha:&a];
    int rgb = (int) (r * 255.0f)<<16 | (int) (g * 255.0f)<<8 | (int) (b * 255.0f)<<0;
    NSString *colorStr = [NSString stringWithFormat:@"%06x", rgb];
    return colorStr;
}

@end